<template>
  <div class="query-form">
    <el-form :model="form" :inline="true">
      <el-row :gutter="10">
        <el-col :span="22">
          <el-input v-model="form.url" @change="changeUrl" @keyup.enter="onSubmit" disabled>
            <template #prepend><span style="margin: 0 10px"
                :style="{ color: methodStyle[form.requestType?.toUpperCase()] }">{{
                  form.requestType
                }}</span></template>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="onSubmit">运行</el-button>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { Close } from '@element-plus/icons-vue'
import { propTypes } from '@/utils/propTypes'
import { ref, watch, onMounted } from 'vue'
import { splitUrl } from '@/utils/url'
import { useMessage } from '@/hooks/useMessage'
const message = useMessage()
const emit = defineEmits(['debug', 'formValue'])
const props = defineProps({
  data: propTypes.object.def({})
})
let form = ref({
  requestType: '',
  protocal: '',
  url: ''
} as any)

const methodStyle = ref({
  GET: '#17b26a',
  POST: '#ef6820',
  DELETE: '#f04438',
  PUT: '#2e90fa'
})

const onSubmit = () => {
  if (!form.value.url) {
    message.warning('请输入正确的URL')
    return
  } else if (form.value.url.indexOf('http') == -1) {
    message.warning('URL格式错误,未包含http://或https://')
    return
  }
  emit('debug')
}

/** url变化处理，并向上发送form */
const changeUrl = async () => {
  const splitUrlList = splitUrl(form.value.url.indexOf('http') != -1 ? form.value.url : '')
  form.value.protocal = splitUrlList?.protocol || 'http'
  emit('formValue', { ...form.value })
}

const init = ()=>{
  form.value.requestType = props.data.requestType || ''
  form.value.url = props.data.url || ''
  const splitUrlList = splitUrl(form.value.url.indexOf('http') != -1 ? form.value.url : '')
  form.value.protocal = splitUrlList?.protocol || 'http'
  emit('formValue', { ...form.value })
}
watch(
  () => props.data,
  () => {
    init()
  },
  {
    deep: true
  }
)

onMounted(async () => {
  init()
})
</script>

<style scoped lang="scss">
:deep(.el-input-group__prepend) {
  padding: 0;

  .service {
    padding: 0 10px;
  }

  .el-select {
    width: 120px;
    margin: 0;
  }
}

.update {
  cursor: pointer;

  &:hover {
    color: #409eff;
    text-decoration: underline;
  }
}
</style>
